//
//  payTopUpViewController.m
//  marrymarry
//
//  Created by lsj on 16/10/11.
//  Copyright © 2016年 cf. All rights reserved.
//
static NSString * chosePayStyleCellID =@"chosePayStyleTableViewCell";
#import "payTopUpViewController.h"
#import "chosePayStyleTableViewCell.h"
#import "handAlipay.h"
#import "HandWxPay.h"
#import "GTMBase64.h"
#import "CommonFunc.h"
#import "WXApiRequestHandler.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import <CommonCrypto/CommonDigest.h>
@interface payTopUpViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    BOOL _isWxPay;
}
@property (weak, nonatomic) IBOutlet UIView *BtnBaseView;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UILabel *myCurrentPriceLabel;
@property (weak, nonatomic) IBOutlet UIButton *SureToPayBtn;
@property (weak, nonatomic) IBOutlet UIButton *SixtyEightBtn;
@property (weak, nonatomic) IBOutlet UIButton *OTEBtn;
@property (weak, nonatomic) IBOutlet UIButton *TSEBtn;
@property (weak, nonatomic) IBOutlet UIButton *FEEBtn;
@property (weak, nonatomic) IBOutlet UIButton *NEEBtn;
@property (weak, nonatomic) IBOutlet UIView *baseView;

@property (weak, nonatomic) IBOutlet UIButton *ONNEBtn;
@property (nonatomic, copy) NSString *paymentcode;
@property (nonatomic,strong) NSMutableDictionary * orderDic;

@property (nonatomic, assign) BOOL isSuccess;
@end

@implementation payTopUpViewController
-(void)viewWillAppear:(BOOL)animated
{
    NSLog(@"viewWillAppear...");
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(backPage:)
                                                 name:@"payCallBack"
                                               object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    NSLog(@"viewWillDisappear...");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.layer.cornerRadius = 5;
    self.baseView.layer.cornerRadius = 5;
    self.SureToPayBtn.layer.cornerRadius = 5;
    self.SixtyEightBtn.layer.cornerRadius = 5;
    self.SixtyEightBtn.layer.borderWidth = 0.5;
    self.SixtyEightBtn.layer.borderColor = RGB(236,236, 236).CGColor;
    self.OTEBtn.layer.cornerRadius = 5;
    self.OTEBtn.layer.borderWidth = 0.5;
    self.OTEBtn.layer.borderColor = RGB(236,236, 236).CGColor;
    self.TSEBtn.layer.cornerRadius =5;
    self.TSEBtn.layer.borderWidth = 0.5;
    self.TSEBtn.layer.borderColor = RGB(236,236, 236).CGColor;
    self.FEEBtn.layer.cornerRadius = 5;
    self.FEEBtn.layer.borderWidth = 0.5;
    self.FEEBtn.layer.borderColor = RGB(236,236, 236).CGColor;
    self.NEEBtn.layer.cornerRadius = 5;
    self.NEEBtn.layer.borderWidth = 0.5;
    self.NEEBtn.layer.borderColor = RGB(236,236, 236).CGColor;
    self.ONNEBtn.layer.cornerRadius = 5;
    self.ONNEBtn.layer.borderWidth = 0.5;
    self.ONNEBtn.layer.borderColor = RGB(236,236, 236).CGColor;
    
    self.myTableView.scrollEnabled = NO;
    [self.myTableView registerNib:[UINib nibWithNibName:chosePayStyleCellID bundle:nil] forCellReuseIdentifier:chosePayStyleCellID];
}
///68
- (IBAction)SEBtn:(UIButton *)sender {
    sender.backgroundColor = RGB(226, 254, 243);
    for (UIButton * btn in self.BtnBaseView.subviews) {
        if (btn != sender) {
            btn.backgroundColor = [UIColor whiteColor];
        }
    }
    
    self.myCurrentPriceLabel.text =@"68.00";
}
///128
- (IBAction)OTEBtnSelect:(UIButton *)sender {
    sender.backgroundColor = RGB(226, 254, 243);;
    for (UIButton * btn in self.BtnBaseView.subviews) {
        if (btn != sender) {
            btn.backgroundColor = [UIColor whiteColor];
        }
    }
    self.myCurrentPriceLabel.text =@"128.00";
}
///278
- (IBAction)TSEBtnSelect:(UIButton *)sender {
    sender.backgroundColor = RGB(226, 254, 243);;
    for (UIButton * btn in self.BtnBaseView.subviews) {
        if (btn != sender) {
            btn.backgroundColor = [UIColor whiteColor];
        }
    }
    self.myCurrentPriceLabel.text =@"278.00";
}

///588
- (IBAction)FEEBtnSelect:(UIButton *)sender {
    sender.backgroundColor = RGB(226, 254, 243);;
    for (UIButton * btn in self.BtnBaseView.subviews) {
        if (btn != sender) {
            btn.backgroundColor = [UIColor whiteColor];
        }
    }
    self.myCurrentPriceLabel.text =@"588.00";
}

///988
- (IBAction)NEEBtnSelect:(UIButton *)sender {
    sender.backgroundColor = RGB(226, 254, 243);;
    for (UIButton * btn in self.BtnBaseView.subviews) {
        if (btn != sender) {
            btn.backgroundColor = [UIColor whiteColor];
        }
    }
    self.myCurrentPriceLabel.text =@"988.00";
}

///1998
- (IBAction)ONNEBtnSelect:(UIButton*)sender {
    sender.backgroundColor = RGB(226, 254, 243);;
    for (UIButton * btn in self.BtnBaseView.subviews) {
        if (btn != sender) {
            btn.backgroundColor = [UIColor whiteColor];
        }
    }
    self.myCurrentPriceLabel.text =@"1998.00";
}




#pragma mark -----UITableViewDataSource,UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    chosePayStyleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:chosePayStyleCellID];
    if (!cell) {
        cell = [[chosePayStyleTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:chosePayStyleCellID];
        
    }
    [cell reloadTheStyleWithIndexPath:indexPath andSelectedWX:_isWxPay];
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 50;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0) {
        _isWxPay = YES;
        
        self.paymentcode = WXPAY;
        //        [self goForPayWithDic:self.orderDic];
    }else
    {
        _isWxPay = NO;
        self.paymentcode = ALIPAY;
        //        [self goForPayWithDic:self.orderDic];
        
    }
    
    [self.myTableView reloadData];
    
}






- (void)goForPayWithDic:(NSDictionary *)dic
{
    NSString * moneyStr = self.myCurrentPriceLabel.text;
    NSLog(@"moneyStr ====== %@",moneyStr);
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    [dictM setValue:[NSNumber numberWithInt:[[Tools getValueFromNSUserDefaultsByKey:USERID] intValue]] forKey:@"userId"];
    [dictM setValue:[NSNumber numberWithInt:2] forKey:@"clientType"];
    [dictM setValue:@"0.01" forKey:@"payMoney"];
    [dictM setValue:[NSNumber numberWithInt:2] forKey:@"type"];
    if (_isWxPay) {
        [dictM setValue:[NSNumber numberWithInt:1] forKey:@"payType"];
    }else{
        [dictM setValue:[NSNumber numberWithInt:2] forKey:@"payType"];
    }
    
    NSDate *fromdate=[NSDate date];
    NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSString* datestring=[dateFormat stringFromDate:fromdate];
    [dictM setValue:datestring forKey:@"timeStamp"];
    
    NSString *msd = [NSString stringWithFormat:@"%@%@%@%@",[Tools getValueFromNSUserDefaultsByKey:USERID],@"2",@"0.01",datestring];
    [dictM setValue:[self md5:msd] forKey:@"md5Str"];
    NSLog(@"dictM ======== %@",dictM);

    NSString *stringsJson = [self dictionaryToJson:dictM];
    
    NSData *datasss=[stringsJson dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString * str = [[NSString alloc] initWithData:[GTMBase64 encodeData:datasss] encoding:NSUTF8StringEncoding];
   
    if([str rangeOfString:@"="].location !=NSNotFound || [str rangeOfString:@"=="].location !=NSNotFound)//_roaldSearchText
    {
        str = [str stringByReplacingOccurrencesOfString:@"=" withString:@"."];
        
    }
    else
    {
        NSLog(@"no");
    }
    NSDictionary *dicBase64=@{@"":str};
    
    
    
    NSString * payStr;
    if (_isWxPay) {
        payStr = GOWXPAY_URL;
    }else
    {
        payStr = GOALIPAY_URL;
    }
    [[LJFNetworkingManager shareManager] POST:payStr parameters:dicBase64 success:^(id returnData, int code, NSString *msg)
     {
         NSLog(@"%@",returnData);
         //       [self payWithDict:returnData];
         if (code == 1) {
             if (_isWxPay) {
                 NSString  * jsonString = [CommonFunc textFromBase64String:returnData];
                 
                 NSDictionary *weChatDict = [self parseJSONStringToNSDictionary:jsonString];
                 NSLog(@"weChatDict === %@",weChatDict);
                 /** 去微信支付 **/
                 
                 NSString *res = [WXApiRequestHandler jumpToBizPay:weChatDict];
                 
                 if( ![@"" isEqual:res] ){
                     UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"支付失败" message:res delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                     
                     [alter show];
                 }
                 
             }else{
                 NSLog(@"dic[data] ========== %@",returnData);
                 NSString * baseStr64 = returnData;
                 NSString * str = [GTMBase64 decodeBase64String:baseStr64];
                 NSData *posonData = [[NSData alloc] initWithData:[str dataUsingEncoding:NSUTF8StringEncoding]];
                 NSDictionary *posonDic = [NSJSONSerialization JSONObjectWithData:posonData options:NSJSONReadingMutableLeaves error:nil];
                 NSLog(@"posonDic ======== %@",posonDic);
                 [self startAlipayWithDic:posonDic];
                 
             }
         }
         
         
         
         
     } failure:^(NSError *error)
     {
         
     } showHUD:nil];
}



-(NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}

- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
- (NSString *)md5:(NSString *)str
{
    const char * cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}


+ ( NSString *)md5StringNB:( NSString *)str

{
    
    const char *myPasswd = [str UTF8String ];
    
    unsigned char mdc[ 16 ];
    
    CC_MD5 (myPasswd, ( CC_LONG ) strlen (myPasswd), mdc);
    
    NSMutableString *md5String = [ NSMutableString string ];
    
    [md5String appendFormat : @"%02x" ,mdc[ 0 ]];
    
    for ( int i = 1 ; i< 16 ; i++) {
        
        [md5String appendFormat : @"%02x" ,mdc[i]^mdc[ 0 ]];
        
    }
    
    return md5String;
    
}


//支付宝支付
-(void)startAlipayWithDic:(NSDictionary *)cfDic;
{
    
    
    
    NSString *partner = PartnerID;//PID
    NSString *seller = SellerID;      //谢国雄支付宝账户
    NSString *privateKey = PartnerPrivKey;
    
    NSLog(@"%@",privateKey);
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.sellerID = seller;
    order.outTradeNO = cfDic[@"outTradeNo"]; //订单ID（由商家自行制定）[self generateTradeNO]
    order.subject = @"你来约充值支付"; //商品标题
    order.body = @"只需要付哦"; //商品描述
    order.totalFee=@"0.01";
    order.notifyURL =  ALIPAYRETURN_URL; //回调URL
    //    order.totalFee = @"31.00"; //商品价格
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"2";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showURL = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"marry";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    
    //id <DataVerifier>verifier = CreateRSADataVerifier(privateKey);
    
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSNotification* notification = [NSNotification notificationWithName:@"payCallBack" object:resultDic userInfo:nil];
            [[NSNotificationCenter defaultCenter] postNotification:notification];
        }];
    }
    
    
    
}


#pragma marp - 支付宝回调
-(void)backPage:(NSNotification *)notification
{
    
    NSDictionary * dict = [notification object];
    NSString *message = @"";
    if(dict != nil && [dict objectForKey:@"ret"] != nil)
    {
        
        if([[dict objectForKey:@"ret"] isEqualToString:@"0"])
        {
            message = @"您已经支付成功！";
            self.isSuccess = YES;
            
            if (self.successBlock)
            {
                self.successBlock();
            }
            
        }else
        {
            message = @"支付失败，请重新支付。";
            self.isSuccess = NO;
        }
    }else if (dict != nil && [dict objectForKey:@"resultStatus"] != nil){
        if([[dict objectForKey:@"resultStatus"] isEqualToString:@"9000"])
        {
            message = @"您已经支付成功！";
            self.isSuccess = YES;
            
            if (self.successBlock)
            {
                self.successBlock();
            }
            
        }else{
            message = @"支付失败，请重新支付。";
            self.isSuccess = NO;
        }
    }
    
    if(![message isEqualToString:@""])
    {
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    NSLog(@"发送支付通知");
}


#pragma mark -----------------------支付失败或者成功
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (self.isSuccess)
    {
//        [self requestTheNetWith:nil andURL:MYALLINFO_URL andDic:@{@"id":[Tools getValueFromNSUserDefaultsByKey:USERID]}];
        NSLog(@"充值成功");
//        [self removeFromParentViewController];
        [SVProgressHUD showSuccessWithStatus:@"充值成功"];
        
        
    }else
    {
        NSLog(@"支付失败");
        [SVProgressHUD showErrorWithStatus:@"充值失败"];
    }
    [self.navigationController popViewControllerAnimated:YES];
     self.view.hidden = YES;
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark --------------网络请求
-(void)requestTheNetWith:(NSArray *)myRequestArry andURL:(NSString *)myurl andDic:(NSDictionary *)myDic;
{
    if (myRequestArry.count>0) {
        [[LJFNetworkingManager shareManager] POST:myurl upLoadImages:myRequestArry parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            
        } failure:^(NSError *error) {
            NSLog(@"失败");
            
        } showHUD:self.view];
        
    }else
    {
        [[LJFNetworkingManager shareManager] POST:myurl parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            
            } failure:^(NSError *error) {
            NSLog(@"%@",error);
        } showHUD:self.view];
        
    }
    
    
}


- (IBAction)sureToPay:(UIButton *)sender {
    NSLog(@"确定支付");
    if (_isWxPay) {
        self.paymentcode = WXPAY;
        [self goForPayWithDic:self.orderDic];
    }else
    {
        self.paymentcode = ALIPAY;
        [self goForPayWithDic:self.orderDic];
    }
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
